//
//  SWProfileViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/12/14.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWProfileViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,ClickActionDelegate
{
    private enum SettingAction:Int
    {
        case Account
        case Order
        case About
        case Feedback
        case Logout
        case Setting
        case Evaluate
        case ModifyChildInfo
        case Recommend
    }
    
    private class SettingItem
    {
        var title:String
        var sub:Bool
        var action:SettingAction
        var rowHeight:CGFloat
        var icon:UIImage?
        
        init(title:String, sub:Bool, action:SettingAction, rowHeight:CGFloat)
        {
            self.title = title
            self.sub = sub
            self.action = action
            self.rowHeight = rowHeight
        }
    }
    
    private let SeparatorInset = UIEdgeInsetsMake(0, 15, 0, 15)
    private var _settings:[SettingItem] = []
    private var _tableView = UITableView()
    private var _headerView:SWProfileHeaderView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    deinit
    {
        trace("DEINIT SWProfileViewController")
        NotificationCenter.default.removeObserver(self)
    }
    
    override var prefersNavigationBarHidden: Bool
    {
        return true
    }
    
    private func setup()
    {
        //-----意见反馈
        let modifyChildInfoItem = SettingItem(title: "宝宝资料", sub: false, action:.ModifyChildInfo, rowHeight:55)
        modifyChildInfoItem.icon = UIImage(named: "profile_icon_cell")
        _settings.append(modifyChildInfoItem)
        
        //-----意见反馈
        let orderItem = SettingItem(title: "订单", sub: false, action:.Order, rowHeight:55)
        orderItem.icon = UIImage(named: "profile_icon_cell")
        _settings.append(orderItem)
        
        //-----意见反馈
        let feedbackItem = SettingItem(title: "意见反馈", sub: false, action:.Feedback, rowHeight:55)
        feedbackItem.icon = UIImage(named: "profile_icon_cell")
        _settings.append(feedbackItem)
        
        //-----评分
        let evaluateItem = SettingItem(title: "五分好评", sub: false, action:.Evaluate, rowHeight:55)
        evaluateItem.icon = UIImage(named: "profile_icon_cell")
        _settings.append(evaluateItem)
        
        //-----评分
        let recommendItem = SettingItem(title: "推荐给好友", sub: false, action:.Recommend, rowHeight:55)
        recommendItem.icon = UIImage(named: "profile_icon_cell")
        _settings.append(recommendItem)
        
        //-----设置
        let settingItem = SettingItem(title: "设置", sub: false, action:.Setting, rowHeight:55)
        settingItem.icon = UIImage(named: "profile_icon_cell")
        _settings.append(settingItem)
        
        
        
        let tableHeaderView:UIView = UIView()
        tableHeaderView.backgroundColor = UIColor(hex: 0xefefef)
        
        let headerView = SWProfileHeaderView(frame: CGRectMake(0,0,view.width,124))
        headerView.image = SWAccountManager.sharedManager().account?.avatarURL
        headerView.delegate = self
        tableHeaderView.addSubview(headerView)
        _headerView = headerView
        
        let grid:CGFloat = 9
        let chartView:SWProfileChartView = SWProfileChartView(frame: CGRectMake(0,headerView.bottom + grid,view.width,0))
        tableHeaderView.addSubview(chartView)
        tableHeaderView.height = chartView.bottom + grid
        
        let bookView:SWProfileBookView = SWProfileBookView(frame: CGRectMake(0,chartView.bottom + grid,view.width,130))
        bookView.delegate = self
        tableHeaderView.addSubview(bookView)
        tableHeaderView.height = bookView.bottom + grid
        
        _tableView.frame = view.bounds
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.rowHeight = 55
        _tableView.backgroundColor = UIColor.white
        _tableView.tableHeaderView = tableHeaderView
        _tableView.tableFooterView = UIView()
        _tableView.separatorColor = UIColor(hex: 0xe1e1e1)
        view.addSubview(_tableView)
        _tableView.separatorInset = SeparatorInset
        if #available(iOS 8.0, *) {
            _tableView.layoutMargins = SeparatorInset
        }
        
        let backBtn:UIButton = UIButton(type: .custom)
        backBtn.setImage(UIImage(named:"global_btn_back"), for: .normal)
        backBtn.sizeToTouchEasy()
        backBtn.center = CGPointMake(18, 41)
        backBtn.addTarget(self, action: #selector(backBtnTapped), for: .touchUpInside)
        view.addSubview(backBtn)
        
        NotificationCenter.default.addObserver(self, selector: #selector(accountInfoChanged(_:)), name: NotificationName.AccountInfoChanged, object: nil)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _settings.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell:UITableViewCell?
        if let item = _settings.valueAt(indexPath.row)
        {
            let identifier:String = "Cell"
            cell = tableView.dequeueReusableCell(withIdentifier: identifier)
            if cell == nil
            {
                cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
                if #available(iOS 8.0, *) {
                    cell?.layoutMargins = SeparatorInset
                }
                else{
                    cell?.separatorInset = SeparatorInset
                }
            }
            
            cell?.accessoryType = item.sub ? .disclosureIndicator : .none
            cell?.textLabel?.textColor = UIColor(hex: 0x323232)
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 13)
            cell?.textLabel?.text = item.title
            cell?.imageView?.image = item.icon
        }
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
        if let item = _settings.valueAt(indexPath.row)
        {
            if item.action == .Feedback
            {
                navigationController?.pushViewController(SWFeedbackViewController(), animated: true)
            }
            else if item.action == .Order
            {
                navigationController?.pushViewController(SWOrderListViewController(), animated: true)
            }
            else if item.action == .Setting
            {
                navigationController?.pushViewController(SWGeneralSettingViewController(), animated: true)
            }
            else if item.action == .ModifyChildInfo
            {
                if let child = SWAccountManager.sharedManager().account?.child
                {
                    let viewController = SWChildProfileSettingViewController(child: child)
                    navigationController?.pushViewController(viewController, animated: true)
                }
            }
            else if item.action == .Evaluate
            {
                if let url = URL(string: SW.Config.APP_STORE_URL){
                    UIApplication.shared.openURL(url)
                }
            }
            else if item.action == .Recommend
            {
                SWSharePresenter.instance.show {action in
                    let url:String = "http://www.bbyiya.com"
                    let channel:SWShareChannel = SWShareAction.getShareChannelFormAction(action: action)
                    SWShareManager.sharedManager().share(url: url, channel: channel)
                }
            }
        }
    }
    
    func view(_ view:UIView, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Tap
        {
            if view is SWProfileHeaderView
            {
                if let account = SWAccountManager.sharedManager().account
                {
                    let viewController = SWUserProfileSettingViewController(account: account)
                    navigationController?.pushViewController(viewController, animated: true)
                }
            }
            else
            {
                let bookID:String = aArgument?[SWKey.bookID] as? String ?? ""
                let pageID:String = aArgument?[SWKey.pageID] as? String ?? ""
                let bookViewController = SWBookViewController()
                bookViewController.bookID = bookID
                bookViewController.pageID = pageID
                navigationController?.pushViewController(bookViewController, animated: true)
            }
        }
    }
    
    //返回按钮
    @objc private func backBtnTapped()
    {
        navigationController?.popViewController(animated: true)
    }
    
    
    @objc private func accountInfoChanged(_ notification:Notification)
    {
        trace("accountInfoChanged", notification.userInfo)
        if let avatarURL = notification.userInfo?[SWModifyUserInfoKey.avatarURL] as? String
        {
            _headerView?.image = avatarURL
        }
    }
    
}
